<?php
namespace App\library\services;


use App\library\common\Curl;
use App\Models\Agent;
use App\Models\WxUser;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class WeChatService extends BaseServices
{

    /**
     * Author:Yingbo Sun
     * 微信登录换取openid
     * @param $code
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function WeChatLogin($code,$type = '')
    {
        if (empty($code)) {
            return ['code' => 400,'message' => '参数错误','data' => []];
        }
        $appId = config('setting.WeChat.appId');
        $secret = config('setting.WeChat.secret');
        //请求地址
        $url = config('setting.WeChat.url')."?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        $url = sprintf($url,$appId,$secret,$code);
        //申请请求客户端
        $res = Curl::geturl($url);
        if ($type == 'user'){
            $model = new WxUser();
        }else{
            $model = new Agent();
        }
        return self::firstOrCreate($model, $res['openid']);
    }

    /**
     * Author:Yingbo Sun
     * 查询或创建  加密uid  获取token
     * @param $model
     * @param $openid
     * @return mixed
     */
    public static function firstOrCreate($model, $openid)
    {
        $data = $model->where('wx_openid',$openid)->first();
        if (!empty($data)){
            $uid = $data->id;
        }else{
            $uid = $model->create(['wx_openid'=>$openid])->id;
        }
        $uid = encrypt($uid);
        return Jwt::signToken($uid);
    }
}
